﻿
using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Net;
using System.Xml.Serialization;
using System.IO;
using System.Text;
using System.Xml;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Timers;

using MediaPortal.GUI.Library;
using MediaPortal.Dialogs;
using MediaPortal.Util;
using MediaPortal.Localisation;
using MediaPortal.Configuration;
using MediaPortal.Player;
using MediaPortal.Playlists;
using MediaPortal.Music.Database;
using OpenSocialPlugin.Helper_Classes;
using OpenSocialPlugin.Providers;
using OpenSocialPlugin.General;

namespace OpenSocialPlugin
{
  public enum View
  {
    List = 0,
    Icons = 1,
    BigIcons = 2,
    Albums = 3,
    PlayList = 4,
    Filmstrip = 5
  }

  public class OpenSocialPlugin : DefaulGUI, ISetupForm 
  {

    #region MapSettings class
    [Serializable]
    public class MapSettings
    {
      protected int _SortBy;
      protected int _ViewAs;
      protected bool _SortAscending;

      public MapSettings()
      {
        // Set default view
        _SortBy = 0;
        _ViewAs = (int)View.BigIcons;
        _SortAscending = true;
      }

      [XmlElement("SortBy")]
      public int SortBy
      {
        get { return _SortBy; }
        set { _SortBy = value; }
      }

      [XmlElement("ViewAs")]
      public int ViewAs
      {
        get { return _ViewAs; }
        set { _ViewAs = value; }
      }

      [XmlElement("SortAscending")]
      public bool SortAscending
      {
        get { return _SortAscending; }
        set { _SortAscending = value; }
      }
    }
    #endregion

    #region Base variables

    #endregion


    #region locale vars


    private Stack NavigationStack = new Stack();
    MapSettings mapSettings = new MapSettings();
    ISocialSite _curentsite;

    //static GUIDialogProgress dlgProgress;

 
    #endregion

    #region skin connection
    [SkinControlAttribute(50)]
    protected GUIFacadeControl listControl = null;
    //[SkinControlAttribute(2)]
    //protected GUISortButtonControl sortButton = null;
    //[SkinControlAttribute(2)]
    //protected GUIButtonControl homeButton = null;
    [SkinControlAttribute(3)]
    protected GUIButtonControl btnSwitchView = null;
    [SkinControlAttribute(5)]
    protected GUIButtonControl friendsButton = null;
    [SkinControlAttribute(6)]
    protected GUIButtonControl photosButton = null;
    [SkinControlAttribute(7)]
    protected GUIButtonControl searchButton = null;
    [SkinControlAttribute(8)]
    protected GUIButtonControl extrasButton = null;
    [SkinControlAttribute(9)]
    protected GUIButtonControl providerButton = null;
    [SkinControlAttribute(106)]
    protected GUIImage imgThumb = null;

    #endregion


    public OpenSocialPlugin()
    {
      _setting.Load();
      StaticHelper.settings = _setting;
      GetID = GetWindowId();
      updateStationLogoTimer.AutoReset = true;
      updateStationLogoTimer.Enabled = false;
      updateStationLogoTimer.Elapsed += new ElapsedEventHandler(OnDownloadTimedEvent);
      Client.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadLogoEnd);
       GUIWindowManager.Receivers += new SendMessageHandler(GUIWindowManager_Receivers);
 
    }
    OSP_Person _selectedPerson;
    public OSP_Person SelectedPerson
    {
        get
        {
            return _selectedPerson;
        }
        set
        {
            _selectedPerson = value;
            if (_selectedPerson != null)
              SetPerson(_selectedPerson);
        }
    }
 
    void GUIWindowManager_Receivers(GUIMessage message)
    {
    }

    #region ISetupForm Members
    // return name of the plugin
    public string PluginName()
    {
      return _setting.PluginName;
    }
    // returns plugin description
    public string Description()
    {
      return "Plugin for expose the social sites contents";
    }
    // returns author
    public string Author()
    {
      return "Dukus";
    }
    // shows the setup dialog
    public void ShowPlugin()
    {
      SetupForm setup = new SetupForm();
      setup._settings = _setting;
      setup.ShowDialog();
    }
    // enable / disable
    public bool CanEnable()
    {
      return true;
    }
    // returns the unique id again
    public int GetWindowId()
    {
      return 30050;
    }
    // default enable?
    public bool DefaultEnabled()
    {
      return true;
    }
    // has setup gui?
    public bool HasSetup()
    {
      return true ;
    }
    // home button
    public bool GetHome(out string strButtonText, out string strButtonImage,
      out string strButtonImageFocus, out string strPictureImage)
    {
      // set the values for the buttom
      strButtonText = _setting.PluginName;

      // no image or picture
      strButtonImage = String.Empty;
      strButtonImageFocus = String.Empty;
      strPictureImage = "hover_opensocial.png";

      return true;
    }
    // init the skin
    public override bool Init()
    {

      return Load(GUIGraphicsContext.Skin + @"\opensocialbase.xml");
    }

    void provider_OnError(Exception ex)
    {
      
    }
     //do the init before page load
    protected override void OnPageLoad()
    {
        if (StaticHelper.SiteProvider == null)
        {
            GUIWindowManager.ReplaceWindow(30052);
        }
        else
        {
            updateStationLogoTimer.Enabled = true;

            if (NavigationStack.Count == 0 || _curentsite != StaticHelper.SiteProvider)
            {
                //StaticHelper.SiteProvider = new Providers.Facebook();
                StaticHelper.SiteProvider.Init();
                SelectedPerson = StaticHelper.SiteProvider.Login();
                _curentsite = StaticHelper.SiteProvider;
                mapSettings.ViewAs = (int)View.BigIcons;
                ShowPanel();
                ShowList(StaticHelper.SiteProvider.Home());
                GUIControl.FocusControl(GetID, listControl.GetID);
            }
            else
            {
                DoBack();
                GUIControl.FocusControl(GetID, listControl.GetID);
            }

            InitProvider();
        }
        base.OnPageLoad();
    }

    public void InitProvider()
    {
        friendsButton.Disabled = true;
        photosButton.Disabled = true;
        searchButton.Disabled = true;
        extrasButton.Disabled = true;

        if (StaticHelper.SiteProvider.Capabilities.Contains(CapabilitiesEnum.HasFriend))
            friendsButton.Disabled = false;
        if (StaticHelper.SiteProvider.Capabilities.Contains(CapabilitiesEnum.HasPhotos))
            photosButton.Disabled = false;
        if (StaticHelper.SiteProvider.Capabilities.Contains(CapabilitiesEnum.CanSearch))
            searchButton.Disabled = false;
        if (StaticHelper.SiteProvider.Capabilities.Contains(CapabilitiesEnum.HasExtras))
            extrasButton.Disabled = false;
    }

    public void ShowList(GeneralResponse list)
    {
        List<OSP_Person> pers = list.Response as List<OSP_Person>;
        if (pers != null)
        {
            AddPersons(pers);
        }
        List<OSP_Photo> photos = list.Response as List<OSP_Photo>;
        if (photos != null)
        {
            AddPhotos(photos);
        }
        List<OSP_Album> albums = list.Response as List<OSP_Album>;
        if (albums != null)
        {
            AddAlbums(albums);
        }
       GUIPropertyManager.SetProperty("#header.title", list.Title);
    }

    private void LoadFriends(OSP_Person oSP_Person)
    {
        List<OSP_Person> friends = StaticHelper.SiteProvider.GetFriends(oSP_Person);
        if (friends.Count > 0)
        {
            SaveListState(true);
            AddPersons(friends);
            GUIPropertyManager.SetProperty("#header.title", string.Format("Friends of {0} ({1})", oSP_Person, friends.Count));
        }
        else
        {
            Err_message("No items was found !");
        }
        
    }

    private void LoadPhotos(OSP_Album oSP_Album)
    {
        List<OSP_Photo> photos = StaticHelper.SiteProvider.GetPhotos(oSP_Album);
        SaveListState(true);
        AddPhotos(photos);
        GUIPropertyManager.SetProperty("#header.title", oSP_Album.Title);
    }

    private void LoadAlbums(OSP_Person oSP_Person)
    {
        SaveListState(true);
        List<OSP_Album> albums = StaticHelper.SiteProvider.GetAlbums(oSP_Person);
        AddAlbums(albums);

        //GUIDialogMenu dlg = (GUIDialogMenu)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU);
        //if (dlg == null) return;
        //dlg.Reset();
        ////dlg.SetHeading(25653); // Sort options
        //for (int i = 0; i < albums.Count; i++)
        //{
        //    dlg.Add(albums[i].Title);
        //}

        //dlg.DoModal(GetID);
        //if (dlg.SelectedId == -1) return;
        //int select = dlg.SelectedLabel;
        //List<OSP_Photo> photos = StaticHelper.SiteProvider.GetPhotos(albums[select]);
        //SaveListState(true);
        //AddPhotos(photos);
        //GUIPropertyManager.SetProperty("#header.title", albums[select].Title);
    }

    private void AddPhotos(List<OSP_Photo> photos)
    {
        updateStationLogoTimer.Enabled = false;
        downloaQueue.Clear();
        foreach (OSP_Photo photo in photos)
        {
            GUIListItem item = new GUIListItem();
            // and add station name & bitrate
            item.Label = photo.Title;
            string imageFile = GetLocalImageFileName(photo.Thumb);
            if (File.Exists(imageFile))
            {
                item.ThumbnailImage = imageFile;
                //item.IconImage = "defaultVideoBig.png";
                item.IconImage = imageFile;
                item.IconImageBig = imageFile;
            }
            else
            {
                MediaPortal.Util.Utils.SetDefaultIcons(item);
                DownloadImage(photo.Thumb, item);
            }
            item.MusicTag = photo;
            item.OnRetrieveArt += new GUIListItem.RetrieveCoverArtHandler(item_OnRetrieveArt);
            item.OnItemSelected += new GUIListItem.ItemSelectedHandler(item_OnItemSelected);
            listControl.Add(item);
        }
        UpdateGui();
        updateStationLogoTimer.Enabled = true;
    }

    void item_OnRetrieveArt(GUIListItem item)
    {
        OSP_Photo photo = item.MusicTag as OSP_Photo;
        if (photo != null)
        {
            string imageFile = GetLocalImageFileName(photo.Thumb);
            if (File.Exists(imageFile))
            {
                item.ThumbnailImage = imageFile;
                //item.IconImage = "defaultVideoBig.png";
                item.IconImage = imageFile;
                item.IconImageBig = imageFile;
            }
            else
            {
                MediaPortal.Util.Utils.SetDefaultIcons(item);
                DownloadImage(photo.Thumb, item);
            }
        }
    }

    private void AddAlbums(List<OSP_Album> albums)
    {
        updateStationLogoTimer.Enabled = false;
        downloaQueue.Clear();
        foreach (OSP_Album album in albums)
        {
            GUIListItem item = new GUIListItem();
            // and add station name & bitrate
            item.Label = album.Title;
            string imageFile = GetLocalImageFileName(album.Thumb);
            if (File.Exists(imageFile))
            {
                item.ThumbnailImage = imageFile;
                //item.IconImage = "defaultVideoBig.png";
                item.IconImage = imageFile;
                item.IconImageBig = imageFile;
            }
            else
            {
                MediaPortal.Util.Utils.SetDefaultIcons(item);
                DownloadImage(album.Thumb, item);
            }
            item.MusicTag = album;
            item.OnItemSelected += new GUIListItem.ItemSelectedHandler(item_OnItemSelected);
            listControl.Add(item);
        }
        UpdateGui();
        updateStationLogoTimer.Enabled = true;
    }

    private void AddPersons(List<OSP_Person> pers)
    {
        updateStationLogoTimer.Enabled = false;
        downloaQueue.Clear();
        foreach (OSP_Person per in pers)
        {
            GUIListItem item = new GUIListItem();
            // and add station name & bitrate
            item.Label = per.Name;
            string imageFile = GetLocalImageFileName(per.Thumb);
            if (File.Exists(imageFile))
            {
                item.ThumbnailImage = imageFile;
                //item.IconImage = "defaultVideoBig.png";
                item.IconImage = imageFile;
                item.IconImageBig = imageFile;
            }
            else
            {
                MediaPortal.Util.Utils.SetDefaultIcons(item);
                DownloadImage(per.Thumb, item);
            }
            item.MusicTag = per;
            item.OnItemSelected += item_OnItemSelected;
            listControl.Add(item);
        }
      listControl.Sort(new ListComparer());
        UpdateGui();
        updateStationLogoTimer.Enabled = true;
    }



    private void InitList(string queryuri)
    {

    }
    // remeber the selection on page leave
    protected override void OnPageDestroy(int new_windowId)
    {
      SaveListState(false);
      _setting.Save();
      base.OnPageDestroy(new_windowId);
    }
    //// do the clicked action
    protected override void OnClicked(int controlId, GUIControl control, MediaPortal.GUI.Library.Action.ActionType actionType)
    {
      ////
      //// look for button pressed
      ////
      //// record ?
        if (actionType == MediaPortal.GUI.Library.Action.ActionType.ACTION_RECORD)
      {
        //ExecuteRecord();
      }
      else if (control == btnSwitchView)
      {
        switch ((View)mapSettings.ViewAs)
        {
          case View.List:
            mapSettings.ViewAs = (int)View.Icons;
            break;
          case View.Icons:
            mapSettings.ViewAs = (int)View.BigIcons;
            break;
          case View.BigIcons:
            mapSettings.ViewAs = (int)View.Albums;
            break;
          case View.Albums:
            mapSettings.ViewAs = (int)View.Filmstrip;
            break;
          case View.Filmstrip:
            mapSettings.ViewAs = (int)View.List;
            break;
        }
        ShowPanel();
        GUIControl.FocusControl(GetID, control.GetID);
      }
      else if (control == listControl)
      {
        // execute only for enter keys
        if (actionType == MediaPortal.GUI.Library.Action.ActionType.ACTION_SELECT_ITEM)
        {
          // station selected
          DoListSelection();
        }
      }
      //else if (control == sortButton)
      //{
      //  //sort button selected
      //  OnShowSortOptions();
      //}
      else if (control == friendsButton)
      {
          LoadFriends(SelectedPerson);
          GUIControl.FocusControl(GetID, listControl.GetID);
      }
      //else if (control == homeButton)
      //{
      //  DoHome();
      //  GUIControl.FocusControl(GetID, listControl.GetID);
      //}
      else if (control == photosButton)
      {
          LoadAlbums(SelectedPerson);
          GUIControl.FocusControl(GetID, listControl.GetID);
      }
      else if (control == searchButton)
      {
          DoSearch();
      }
      else if (control == extrasButton)
      {
          DoExtras();
      }
      else if (control==providerButton)
      {
        GUIWindowManager.ActivateWindow(30052);
      }
      base.OnClicked(controlId, control, actionType);
    }

    private void DoShowHistory()
    {

    }


    private void DoExtras()
    {
        int serchtype = 0;
        if (StaticHelper.SiteProvider.ExtrasNames != null && StaticHelper.SiteProvider.ExtrasNames.Count > 0)
        {
            GUIDialogMenu dlg = (GUIDialogMenu)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU);
            if (dlg == null) return;
            dlg.Reset();
            dlg.SetHeading("Search option"); // Sort options
            for (int i = 0; i < StaticHelper.SiteProvider.ExtrasNames.Count; i++)
            {
                dlg.Add(StaticHelper.SiteProvider.ExtrasNames[i]);
            }
            dlg.DoModal(GetID);
            if (dlg.SelectedId == -1) return;
            serchtype = dlg.SelectedLabel;
            GeneralResponse resp = StaticHelper.SiteProvider.Extras("", serchtype);
            SaveListState(true);
            ShowList(resp);
        }
        else
        {
            return;
        }
    }


    private void ShowHome(int poz)
    {
      //switch (poz)
      //{
      //  case 0:
      //    GetTimeOpt();
      //    InitList(YouTubeQuery.MostViewedVideo);
      //    break;
      //  case 1:
      //    GetTimeOpt();
      //    InitList(YouTubeQuery.TopRatedVideo);
      //    break;
      //  case 2:
      //    InitList(YouTubeQuery.RecentlyFeaturedVideo);
      //    break;
      //  case 3:
      //    GetTimeOpt();
      //    InitList(YouTubeQuery.MostDiscussedVideo);
      //    break;
      //  case 4:
      //    GetTimeOpt();
      //    InitList(YouTubeQuery.FavoritesVideo);
      //    break;
      //  case 5:
      //    InitList(YouTubeQuery.MostLinkedVideo);
      //    break;
      //  case 6:
      //    InitList(YouTubeQuery.MostRespondedVideo);
      //    break;
      //  case 7:
      //    InitList(YouTubeQuery.MostRecentVideo);
      //    break;
      //  case 8:
      //    InitList(YouTubeQuery.CreateFavoritesUri(null));
      //    break;
      //  case 9:
      //    if (Youtube2MP._settings.LocalFile.Items.Count == 0)
      //    {
      //      Err_message("No downloded item was found !");
      //    }
      //    else
      //    {
      //      SaveListState(true);
      //      foreach (LocalFileStruct entry in Youtube2MP._settings.LocalFile.Items)
      //      {
      //        GUIListItem item = new GUIListItem();
      //        // and add station name & bitrate
      //        item.Label = entry.Title;
      //        item.Label2 = "";
      //        item.IsFolder = false;

      //        string imageFile = Path.GetDirectoryName(entry.LocalFile) + "\\" + Path.GetFileNameWithoutExtension(entry.LocalFile) + ".png";
      //        if (File.Exists(imageFile))
      //        {
      //          item.ThumbnailImage = imageFile;
      //          //item.IconImage = "defaultVideoBig.png";
      //          item.IconImage = imageFile;
      //          item.IconImageBig = imageFile;
      //        }
      //        item.MusicTag = entry;
      //        item.OnItemSelected += new GUIListItem.ItemSelectedHandler(item_OnItemSelected);
      //        listControl.Add(item);
      //      }
      //      GUIPropertyManager.SetProperty("#header.title", Youtube2MP._settings.Cats[9]);
      //      UpdateGui();
      //    }
      //    break;
      //}
    }

    //// override action responses
    public override void OnAction(MediaPortal.GUI.Library.Action action)
    {
        if (action.wID == MediaPortal.GUI.Library.Action.ActionType.ACTION_PREVIOUS_MENU)
      {
        if (listControl.Focus)
        {
          if (NavigationStack.Count > 0)
          {
            DoBack();
            return;
          }
        }
      }

        if (action.wID == MediaPortal.GUI.Library.Action.ActionType.ACTION_PARENT_DIR)
      {
        GUIListItem item = listControl[0];
        
        if ((item != null) && item.IsFolder && (item.Label == ".."))
        {
          DoBack();
          return;
        }
      }
      UpdateGui();
      base.OnAction(action);
    }
    // do regulary updates
    public override void Process()
    {
      // update the gui
      UpdateGui();
      base.Process();
    }

    protected void OnShowSortOptions()
    {
    }
 
    #endregion
    #region helper func's

    private void DoListSelection()
    {
        GUIListItem selectedItem = listControl.SelectedListItem;
        if (selectedItem != null)
        {
            OSP_Person person = selectedItem.MusicTag as OSP_Person;
            if (person != null)
            {
                GUIDialogMenu dlg = (GUIDialogMenu)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU);
                if (dlg == null) return;
                dlg.Reset();
                //dlg.SetHeading(25653); // Sort options
                if (StaticHelper.SiteProvider.Capabilities.Contains(CapabilitiesEnum.HasOtherFriend))
                    dlg.Add("Friends");
                if (StaticHelper.SiteProvider.Capabilities.Contains(CapabilitiesEnum.HasOtherPhotos))
                    dlg.Add("Photos");
                dlg.Add("Info");
                dlg.DoModal(GetID);
                if (dlg.SelectedId == -1) return;
                SelectedPerson = person;
                switch (dlg.SelectedLabelText)
                {
                  case "Friends":
                    {
                      SaveListState(true);
                      LoadFriends(person);
                    }
                    break;
                  case "Photos":
                    {
                      SaveListState(true);
                      LoadAlbums(person);
                    }
                    break;
                  case "Info":
                    {
                      GUIDialogText dlgt =
                        (GUIDialogText) GUIWindowManager.GetWindow((int) Window.WINDOW_DIALOG_TEXT);
                      dlgt.Reset();
                      //dlgt.SetImage(GetLocalImageFileName(person.Thumb));
                      dlgt.SetHeading("Info for person ");
                      dlgt.SetText(StaticHelper.SiteProvider.GetPersonInfo(person));
                      dlgt.DoModal(GetID);
                    }
                    break;
                  default:
                    break;
                }
            }
            OSP_Album album = selectedItem.MusicTag as OSP_Album;
            if (album != null)
            {
                SaveListState(true);
                LoadPhotos(album);
            }
            OSP_Photo photo = selectedItem.MusicTag as OSP_Photo;
            if (photo != null)
            {
                OnShowPicture(photo.Url);
            }
        }
      GUIWaitCursor.Hide();

    }
    
    private void OnShowPicture(string strFile)
    {
        GUISlideShow SlideShow = (GUISlideShow)GUIWindowManager.GetWindow(30051);
        if (SlideShow == null)
        {
            return;
        }

        updateStationLogoTimer.Enabled = false;
        downloaQueue.Clear();
        SlideShow.Reset();
        for (int i = 0; i < listControl.Count; ++i)
        {
            GUIListItem item = listControl[i];
            if (!item.IsFolder)
            {
                if (item.IsRemote)
                {
                    continue;
                }
                OSP_Photo photo = item.MusicTag as OSP_Photo;
                SlideShow.Add(photo.Url);
            }
        }
        updateStationLogoTimer.Enabled = true;
        if (SlideShow.Count > 0)
        {
            //Thread.Sleep(1000);
            GUIWindowManager.ActivateWindow(30051);
            SlideShow.Select(strFile);
        }
    }


    private void DoSearch()
    {
      int serchtype = 0;
      if (StaticHelper.SiteProvider.SearchNames != null && StaticHelper.SiteProvider.SearchNames.Count > 0)
      {
          GUIDialogMenu dlg = (GUIDialogMenu)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU);
          if (dlg == null) return;
          dlg.Reset();
          dlg.SetHeading("Search option"); // Sort options
          for (int i = 0; i < StaticHelper.SiteProvider.SearchNames.Count; i++)
          {
              dlg.Add(StaticHelper.SiteProvider.SearchNames[i]);
          }

          dlg.DoModal(GetID);
          if (dlg.SelectedId == -1) return;
          serchtype = dlg.SelectedLabel;
      }
      else
      {
          return;
      }

      string searchString = "";
      VirtualKeyboard keyboard;
      // display an virtual keyboard
      keyboard = (VirtualKeyboard)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_VIRTUAL_KEYBOARD);
      if (null == keyboard) return;

      keyboard.Reset();
      keyboard.Text = searchString;
      keyboard.DoModal(GetWindowId());
      if (keyboard.IsConfirmed)
      {
        // input confirmed -- execute the search
        searchString = keyboard.Text;
      }

      if ("" != searchString)
      {
          SaveListState(true);
          ShowList(StaticHelper.SiteProvider.Search(searchString, serchtype));
      }
    }


    private void DoBack()
    {
      if (NavigationStack.Count > 0)
      {
        GUIControl.ClearControl(GetID, listControl.GetID);
        NavigationObject obj = NavigationStack.Pop() as NavigationObject;
        obj.SetItems(listControl);
        listControl.SelectedListItemIndex = obj.Position;
        GUIPropertyManager.SetProperty("#header.title", obj.Title);
        mapSettings.ViewAs = (int)obj.CurrentView;
        ShowPanel();
      }
    }
    
    //public void UpdateList()
    //{
   
    //}

    void ShowPanel()
    {
      int itemIndex = listControl.SelectedListItemIndex;
      if (mapSettings.ViewAs == (int)View.BigIcons)
      {
        listControl.CurrentLayout = GUIFacadeControl.Layout.LargeIcons;
      }
      else if (mapSettings.ViewAs == (int)View.Albums)
      {
        listControl.CurrentLayout = GUIFacadeControl.Layout.AlbumView;
      }
      else if (mapSettings.ViewAs == (int)View.Icons)
      {
        listControl.CurrentLayout = GUIFacadeControl.Layout.SmallIcons;
      }
      else if (mapSettings.ViewAs == (int)View.List)
      {
        listControl.CurrentLayout = GUIFacadeControl.Layout.List;
      }
      else if (mapSettings.ViewAs == (int)View.Filmstrip)
      {
        listControl.CurrentLayout = GUIFacadeControl.Layout.Filmstrip;
      }
      else if (mapSettings.ViewAs == (int)View.PlayList)
      {
        listControl.CurrentLayout = GUIFacadeControl.Layout.Playlist;
      }

      if (itemIndex > -1)
      {
        GUIControl.SelectItemControl(GetID, listControl.GetID, itemIndex);
      }
     
    }

    /// <summary>
    /// Called when [show context menu].
    /// </summary>
    protected override void OnShowContextMenu()
    {
      GUIListItem selectedItem = listControl.SelectedListItem;
      
    }


    private void DoOptions()
    {

    }

    private void DoInfo()
    {
      //YahooMusicInfoGUI guiInfo = (YahooMusicInfoGUI)GUIWindowManager.GetWindow(27051);
      //guiInfo.InfoItem = listControl.SelectedListItem.MusicTag as VideoResponse;
      //guiInfo.provider = this.provider;
      //GUIWindowManager.ActivateWindow(27051);
    }

  
    public void UpdateGui()
    {

      string textLine = string.Empty;
      View view = (View)mapSettings.ViewAs;
      bool sortAsc = mapSettings.SortAscending;
      switch (view)
      {
        case View.List:
          textLine = GUILocalizeStrings.Get(101);
          break;
        case View.Icons:
          textLine = GUILocalizeStrings.Get(100);
          break;
        case View.BigIcons:
          textLine = GUILocalizeStrings.Get(417);
          break;
        case View.Albums:
          textLine = GUILocalizeStrings.Get(529);
          break;
        case View.Filmstrip:
          textLine = GUILocalizeStrings.Get(733);
          break;
        case View.PlayList:
          textLine = GUILocalizeStrings.Get(101);
          break;

      }
      GUIControl.SetControlLabel(GetID, btnSwitchView.GetID, textLine);

    }

    void SortChanged(object sender, SortEventArgs e)
    {
      // save the new state
      mapSettings.SortAscending = e.Order != System.Windows.Forms.SortOrder.Descending;
      // update the list
      //UpdateList();
      //UpdateButtonStates();
      GUIControl.FocusControl(GetID, ((GUIControl)sender).GetID);
    }

    #endregion


    public void SetPerson(OSP_Person pers)
    {
        DownloadImage(pers.Thumb, null);
        GUIPropertyManager.SetProperty("#Social.Curent.Person.Thumb", GetLocalImageFileName(pers.Thumb));
    }

   
    private void item_OnItemSelected(GUIListItem item, GUIControl parent)
    {

    }

    private void SaveListState(bool clear)
    {
      if (listControl.ListLayout.ListItems.Count > 0)
      {
        NavigationStack.Push(new NavigationObject(listControl.ListLayout, GUIPropertyManager.GetProperty("#header.title"), listControl.SelectedListItemIndex, (View)mapSettings.ViewAs));
      }
      if (clear)
      {
        GUIControl.ClearControl(GetID, listControl.GetID);
      }
    }
    

  }
}
